package com.vjwealth.android.nos.activity

import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.TranslateAnimation
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.Button
import android.widget.CompoundButton
import android.widget.LinearLayout
import com.android.volley.Request
import com.android.volley.Response
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.vjwealth.android.nos.Constants
import com.vjwealth.android.nos.R
import com.vjwealth.android.nos.activity.main.MainActivity
import com.vjwealth.android.nos.base.BaseActivity
import com.vjwealth.android.nos.base.BaseApplication
import com.vjwealth.android.nos.entity.LoginData
import com.vjwealth.android.nos.entity.LoginEntity
import com.vjwealth.android.nos.entity.Result
import com.vjwealth.android.nos.http.Api
import com.vjwealth.android.nos.http.BaseStringRequest
import com.vjwealth.android.nos.http.VolleyUtils
import com.vjwealth.android.nos.service.MusicService
import com.vjwealth.android.nos.utils.CountDownTimerUtils
import com.vjwealth.android.nos.utils.NetworkUtils
import com.vjwealth.android.nos.utils.ParamsUtils
import com.vjwealth.android.nos.utils.RegexPatternUtils
import kotlinx.android.synthetic.main.activity_start.*
import kotlinx.android.synthetic.main.layout_start_page.*
import kotlinx.android.synthetic.main.layout_title.*
import kotlinx.android.synthetic.main.layout_user_agreements.*
import org.json.JSONObject


class StartActivity : BaseActivity(), View.OnClickListener{
    override fun onClick(v: View?) {
        if(v != null){
            when(v.id){
                //启动时的中间按钮
                mCenterStartBtn.id -> startApp()
                //登录界面相关
                mLoginCodeBtn.id -> fetchLoginCode(mLoginPhoneView.text.toString(), mLoginCodeBtn)
                mLoginQQBtn.id -> loginQQ()
                mLoginWXBtn.id -> loginWX()
                mLoginBtn.id -> login()
                //注册界面相关
                mSignCodeBtn.id -> fetchLoginCode(mSignPhoneView.text.toString(), mSignCodeBtn)
                mSignBtn.id -> sign()
                //协议界面相关
                mAgreeBtn.id -> agree()
                //切换
                mToLoginBtn.id -> toLoginView()
                mToSignBtn.id -> toSignView()
            }
        }
    }
    //短信验证码倒计时
    private var mCountDownTimerUtils: CountDownTimerUtils? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mShowTitleLayout = false
        setContentView(R.layout.activity_start)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        initView()
    }

//    override fun attachBaseContext(newBase: Context) {
//        super.attachBaseContext(object : ContextWrapper(newBase) {
//            override fun getSystemService(name: String): Any {
//                return if (Context.AUDIO_SERVICE == name) applicationContext.getSystemService(name) else super.getSystemService(name)
//            }
//        })
//    }

    override fun onBackPressed() {
        super.onBackPressed()
        BaseApplication.instance.getActivityManager().popAllActivity()
    }

    private fun initView(){
        mCenterStartBtn.setOnClickListener(this@StartActivity)
        mLoginCodeBtn.setOnClickListener(this@StartActivity)
        mLoginBtn.setOnClickListener(this@StartActivity)
        mSignCodeBtn.setOnClickListener(this@StartActivity)
        mSignBtn.setOnClickListener(this@StartActivity)
        mToLoginBtn.setOnClickListener(this@StartActivity)
        mToSignBtn.setOnClickListener(this@StartActivity)
        mAgreeBtn.setOnClickListener(this@StartActivity)
        mLoginQQBtn.setOnClickListener(this@StartActivity)
        mLoginWXBtn.setOnClickListener(this@StartActivity)
        mAgreeCheckBox.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            mAgreeBtn.isEnabled = isChecked
            if(isChecked){
                mAgreeBtn.setBackgroundResource(R.mipmap.user_agree_bg)
            }else{
                mAgreeBtn.setBackgroundResource(R.mipmap.user_agree_normal_bg)
            }
        })

        mTitleNameView.text = "用户协议"
        mLayoutStart.visibility = View.VISIBLE
        mLayoutAgree.visibility = View.GONE
        Glide.with(this@StartActivity).load(R.mipmap.start_notifylight).asGif().into(mCenterStartBtn)
        var videoPath = Uri.parse("android.resource://"+packageName+"/"+R.raw.background_gif).toString()
        mVideoView.setVideoPath(videoPath)
        mVideoView.start()
        mVideoView.setOnPreparedListener(MediaPlayer.OnPreparedListener { mediaPlayer ->
            mediaPlayer.start()
            mediaPlayer.isLooping = true
        })

        mVideoView.setOnCompletionListener(MediaPlayer.OnCompletionListener { mediaPlayer ->
            mVideoView.setVideoPath(videoPath)
            mVideoView.start()
        })
    }

    /**数据处理************************************************************************************/
    private fun saveLoginInfor(loginData: LoginData){
        BaseApplication.spInfor!!.putString(Constants.LOGIN_ACCOUNT, loginData.account)
        BaseApplication.spInfor!!.putString(Constants.LOGIN_USER_ID, loginData.customerId.toString())
        BaseApplication.spInfor!!.putString(Constants.LOGIN_INVITATION_CODE, loginData.invitationCode)
        BaseApplication.spInfor!!.putString(Constants.LOGIN_MOBILE_PHONE, loginData.phone)
        BaseApplication.spInfor!!.putString(Constants.LOGIN_TOKEN, "Bearer "+loginData.token)
    }
    /**界面显示************************************************************************************/
    //切换动画
    private fun startTranslateAnimation(v: Float, v1: Float, v2: Float, v3: Float, view: View, time: Long){
        var animationSet01 = AnimationSet(true)
        var translateAnimation01 = TranslateAnimation(
                Animation.RELATIVE_TO_SELF, v,
                Animation.RELATIVE_TO_SELF, v1,
                Animation.RELATIVE_TO_SELF, v2,
                Animation.RELATIVE_TO_SELF, v3)
        translateAnimation01.duration = time
        translateAnimation01.fillAfter = true
        animationSet01.addAnimation(translateAnimation01)
        view.animation = animationSet01

    }
    //中间的启动按钮
    private fun startApp(){
        if(NetworkUtils.isAvailable(this)){
            var serviceIntent = Intent(applicationContext, MusicService::class.java)
            startService(serviceIntent)
            var loginPhone = BaseApplication.spInfor!!.getString(Constants.LOGIN_MOBILE_PHONE)
            if(!TextUtils.isEmpty(loginPhone)){
                toMainActivity()
            }else{
                mCenterStartBtn.visibility = View.GONE
                mLoginLayout.visibility = View.VISIBLE
                startTranslateAnimation(1.0f, 0.0f, 0.0f, 0.0f, mLoginLayout, 500)
            }
        }else{
            showExceptionMessage(resources.getString(R.string.network_exception))
        }
        checkVersion()
    }
    //显示登录界面
    private fun toLoginView(){
        mLoginLayout.visibility = View.VISIBLE
        mSignLayout.visibility = View.GONE
    }
    //显示注册界面
    private fun toSignView(){
        toWebView()
        mLayoutStart.visibility = View.GONE
        mLoginLayout.visibility = View.GONE
        mSignLayout.visibility = View.GONE
        mLayoutAgree.visibility = View.VISIBLE
    }
    //显示协议界面
    private fun toWebView(){
        mWebViewLayout.removeAllViews()
        var params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        var webView = WebView(applicationContext)
        webView.layoutParams = params
        mWebViewLayout.addView(webView)

        var webSetting = webView.settings
        webSetting.javaScriptEnabled = true
        webSetting.useWideViewPort = true
        webSetting.loadWithOverviewMode = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webView.setBackgroundColor(0)
        webView.loadUrl(Api.REGISTER_PROTOCOL)
    }
    //同意协议
    private fun agree(){
        mLayoutAgree.visibility = View.GONE
        mLayoutStart.visibility = View.VISIBLE
        mLoginLayout.visibility = View.GONE
        mSignLayout.visibility = View.VISIBLE
        mAgreeCheckBox.isChecked = false
    }
    //进入主界面
    private fun toMainActivity(){
        var mainIntent = Intent(this@StartActivity, MainActivity::class.java)
        startActivity(mainIntent)
        this@StartActivity.finish()
    }

    /**接口调用************************************************************************************/
    //获得短信验证码
    private fun fetchLoginCode(phone: String, loginCodeBtn: Button){
        if(!RegexPatternUtils.isPhone(phone)){
            showExceptionMessage("手机号码不正确")
            return
        }
        mCountDownTimerUtils = CountDownTimerUtils(loginCodeBtn, 60000, 1000)
        mCountDownTimerUtils!!.start()
        //TODO 调用发送验证码借款
        var params = ParamsUtils.p_map2string(hashMapOf("mobilePhone" to phone))
        val request = BaseStringRequest(Request.Method.POST, Api.sendCode, params,
                Response.Listener<JSONObject> { response ->
                    val result = Gson().fromJson(response.toString(), Result::class.java)
                    if(!result.meta.success) {
                        showExceptionMessage(result.meta.message)
                    }
                },
                Response.ErrorListener {
                    showExceptionMessage(resources.getString(R.string.network_exception))
                })
        VolleyUtils.requestQueue.add(request)
        VolleyUtils.requestQueue.start()
    }

    //QQ登录
    private fun loginQQ(){}

    //微信登录
    private fun loginWX(){}

    //手机号码登录
    private fun login(){
        //TODO 调用登录接口
        if(!RegexPatternUtils.isPhone(mLoginPhoneView.text.toString())){
            showExceptionMessage(resources.getString(R.string.invalid_mobile))
            return
        }
        if(TextUtils.isEmpty(mLoginCodeView.text.toString())){
            showExceptionMessage(resources.getString(R.string.vericode_is_not_correct))
            return
        }
        var map = hashMapOf<String, String>()
        map.put("code", mLoginCodeView.text.toString())
        map.put("mobilePhone", mLoginPhoneView.text.toString())
        map.put("deviceId", "")
        map.put("userChannelType", "Android")
        var request = BaseStringRequest(Request.Method.POST, Api.login, ParamsUtils.p_map2string(map),
                Response.Listener{ response ->
                    var loginEntity = Gson().fromJson(response.toString(), LoginEntity::class.java)
                    if(loginEntity.meta.success){
                        saveLoginInfor(loginEntity.data)
                        toMainActivity()
                    }else{
                        showExceptionMessage(loginEntity.meta.message)
                    }
                },
                Response.ErrorListener { error ->
                })
        VolleyUtils.requestQueue.add(request)
        VolleyUtils.requestQueue.start()
    }

    //注册
    private fun sign(){
        if(NetworkUtils.isAvailable(this@StartActivity)){
            if(!RegexPatternUtils.isPhone(mSignPhoneView.text.toString())){
                showExceptionMessage(resources.getString(R.string.invalid_mobile))
                return
            }
            if(TextUtils.isEmpty(mSignCodeView.text.toString())){
                showExceptionMessage(resources.getString(R.string.vericode_is_not_correct))
                return
            }
            if(TextUtils.isEmpty(mSignInvitationCodeView.text.toString())){
                showExceptionMessage(resources.getString(R.string.vericode_is_not_correct))
                return
            }
            var map = hashMapOf<String, String>()
            map.put("mobilePhone", mSignPhoneView.text.toString())
            map.put("code", mSignCodeView.text.toString())
            map.put("invitationCodeBy", mSignInvitationCodeView.text.toString())
            map.put("deviceId", "")
            map.put("userChannelType", "Android")
            var request = BaseStringRequest(Request.Method.POST, Api.register, ParamsUtils.p_map2string(map),
                    Response.Listener { response ->
                        var loginEntity = Gson().fromJson(response.toString(), LoginEntity::class.java)
                        if(loginEntity.meta.success){
                            saveLoginInfor(loginEntity.data)
                            toMainActivity()
                        }else{
                            showExceptionMessage(loginEntity.meta.message)
                        }
                    },
                    Response.ErrorListener {

                    })
            VolleyUtils.requestQueue.add(request)
            VolleyUtils.requestQueue.start()

        }
    }

    //版本检查
    private fun checkVersion(){
        if(NetworkUtils.isAvailable(this@StartActivity)){
            var map = hashMapOf("deviceType" to "Android", "appVersion" to mPackageInfo!!.versionName)
            val request = BaseStringRequest(Request.Method.GET, Api.queryNewVersion+ParamsUtils.g_map2string(map),
                    Response.Listener<JSONObject> { response ->
                        val news = response.toString()
//                        showExceptionMessage(news.toString())
                    },
                    Response.ErrorListener {
                        showExceptionMessage("That didn't work!")
                    })
            VolleyUtils.requestQueue.add(request)
            VolleyUtils.requestQueue.start()
        }
    }
}
